package com.example.myapplication;

import static com.gsls.gt.GT.GTApplication.context;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.myapplication.pojo.IotDataObj;
import com.example.myapplication.pojo.Res;
import com.gsls.gt.GT;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Current_Environment_Activity extends AppCompatActivity {
    private TextView Temperature;
    private TextView Humidity;
    private TextView hyVal;
    private TextView amVal;

    private TextView time;
    private QMUITopBar mTopBar;
    private Handler handler;
    private Runnable runnable;

    private NotificationCompat.Builder builder;
    private static final int POLLING_INTERVAL = 3000; // 轮询间隔时间，单位为毫秒
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_environment);
        ActionBar actionBar = getSupportActionBar();

        if (actionBar != null) {
            actionBar.hide();
        }
        mTopBar=findViewById(R.id.c_etopbar);
        QMUIStatusBarHelper.translucent(this);// 沉浸式状态栏
        initTopBar();//初始化状态栏

        Temperature=findViewById(R.id.Temperature);
        Humidity=findViewById(R.id.Humidity);
        hyVal=findViewById(R.id.hyVal);
        amVal=findViewById(R.id.amVal);
        time=findViewById(R.id.time);

        builder = GT.GT_Notification.createNotificationForNormal(
                Current_Environment_Activity.this,
                R.drawable.humidity,
                R.drawable.humidity,//通知栏 右下角图片
                "警告！",//通知栏标题
                //通知栏内容
                "湿度过高，请尽快采取措施",
                true,//通知栏单击是否自动取消
                true,//锁屏后是否弹出
                new Intent(Current_Environment_Activity.this, Current_Environment_Activity.class),//单击跳转的页面
                0,//发送通知栏的时间
                true,//是否 直接启动通知栏
                222//当前通知的 Id编号
        );

    }

    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
        mTopBar.setTitleGravity(Gravity.LEFT);
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
//                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
            }
        });

        mTopBar.setTitle("当前环境情况");
        updatedata();
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                // 在这里执行你的网络请求操作
                new MyAsyncTask().execute();
                // 请求完成后，延迟一段时间再次发送请求
                handler.postDelayed(this, POLLING_INTERVAL);
            }
        };

        handler.post(runnable); // 启动轮询
    }

    private class MyAsyncTask extends AsyncTask<Void, Void, IotDataObj> {

        @Override
        protected IotDataObj doInBackground(Void... voids) {
            // 执行你的异步网络请求操作
            updatedata();
            // 返回请求结果，比如请求到的数据字符串
            return null;
        }

        @Override
        protected void onPostExecute(IotDataObj iotDataObj) {
            // 在UI线程更新UI
//            Temperature.setText(iotDataObj.getTemperature().toString()+"°C");
//            Humidity.setText(iotDataObj.getHumidity().toString()+"%");
//            hyVal.setText(iotDataObj.getHyVal().toString()+"pa");
//            amVal.setText(iotDataObj.getAmVal().toString()+"Lux");
//            dustVal.setText(iotDataObj.getDustVal().toString()+"ppm");
//            time.setText(iotDataObj.getTimestamp().toString());
        }
    }

    private void updatedata(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://1.95.14.5:8883/iot/getcurrentdata")
                .method("GET", null)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("liangxulin",e.getMessage());
                Log.i("liangxulin","error");

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String res = response.body().string();
                Res r = JSON.parseObject(res, Res.class);
                IotDataObj iotDataObj = JSON.parseObject(r.getData().toString(), IotDataObj.class);
                Log.i("liangxulin","success");
                Log.i("liangxulin",iotDataObj.toString());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Random random = new Random();
                        // 生成 1 到 10 之间的随机数
                        int randomNumber1 = random.nextInt(10)+1;
                        int randomNumber2 = random.nextInt(1000)+1;
                        //渲染ui
//                        Temperature.setText(String.valueOf(iotDataObj.getTemperature()+randomNumber1/10)+"°C");
//                        Humidity.setText(String.valueOf(iotDataObj.getHumidity()+randomNumber1/10)+"%");
//                        hyVal.setText(String.valueOf((iotDataObj.getHyVal().doubleValue()+randomNumber2)/1000));
//                        amVal.setText(String.valueOf(iotDataObj.getAmVal()+randomNumber2+"dB"));
                        if (iotDataObj.getHumidity()>70){
                            builder.setContentText("当前湿度为"+iotDataObj.getHumidity()+"%，高于警戒值,请尽快采取措施");
                            GT.GT_Notification.startNotification(builder,222);
                        }
                        Temperature.setText(String.valueOf(iotDataObj.getTemperature())+"°C");
                        Humidity.setText(String.valueOf(iotDataObj.getHumidity())+"%");
                       /* hyVal.setText(String.valueOf(iotDataObj.getCo())+"ppm");
                        amVal.setText(String.valueOf(iotDataObj.getAirQuality())+"mg/m³");*/
                        time.setText(iotDataObj.getTimestamp().toString());
                    }
                });

            }
        });

    }


}